package com.java.study;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Instant;
import java.util.HashMap;

/**
 * @author xuyuansheng
 */
@Slf4j
@RestController
public class MessageProducer {

    @Autowired
    RocketMQTemplate rocketMQTemplate;

    @RequestMapping("send/{times}")
    public Object send(@PathVariable("times") Long times, @RequestBody String message) {
        long epochMilli = Instant.now().toEpochMilli();
        String des = String.format("%s:%s", "testTopic", "tag" + epochMilli);
        for (int i = 0; i < times; i++) {
            HashMap<String, Object> messageHeaders = new HashMap<>();
            messageHeaders.put("KEYS", epochMilli + i);
            Message<String> messageObj = new GenericMessage<>(message, messageHeaders);
            SendResult topicTest = rocketMQTemplate.syncSend(des, messageObj);
            log.info("发送消息成功， status {} 消息ID：{}", topicTest.getSendStatus(), topicTest.getMsgId());
        }
        return "success" + times;
    }


}
